package com.health.work.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import com.health.work.R;
import com.health.work.adapter.QuestionListAdapter;
import com.health.work.model.DoctorExpert;
import com.health.work.model.QuestionBean;
import com.health.work.parse.AddressParse;
import com.health.work.parse.TypeParse;
import com.health.work.utils.AsyncImageLoader;
import com.health.work.utils.DefaultJSONData;
import com.health.work.utils.HEALTHPASSPORT;
import com.health.work.utils.RequestParamtersUtil;
import com.health.work.utils.TipsUtil;
import com.health.work.utils.UserInfoUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * 医生用户登录后的界面
 * 
 * @author star
 * 
 */
public class DoctorUserActivity extends Activity {
	private Button back;
	private Button introduce;
	private String docName;
	private TextView name;
	private TextView noData;
	private ImageView headerImageView;
	private String intro;
	private final static int SUCCESS = 0;
	private final static int FAILE = 1;
	private final static int ERROR = 2;
	private static final int NOASK = 3;
	private static final int SHOWQUESTION = 4;
	private Thread thread;
	protected String errorMessage = "";
	private AsyncImageLoader asyncImageLoader;
	public static ArrayList<QuestionBean> questionList;
	protected QuestionListAdapter adapter;
	private String headerUrl;
	private ListView order_list;
	private Spinner spinner_major;
	protected TypeParse typeParse;
	private String professionalCategoryId = "1";
	protected ProgressDialog dialog;
	protected AddressParse parse;
	private String consultationId;
	private String role;
	private TextView geyan;
	private String geyanString;
	private TextView dangan;
	private String jifenString;
	private String haopingString;
	private String mobilePhoneNum;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:
				setData();
				break;
			case FAILE:
				TipsUtil.showAlert(DoctorUserActivity.this, null, "数据请求失败！");
				break;
			case ERROR:
				TipsUtil.showAlert(DoctorUserActivity.this, null, "未知错误！");
				break;
			case NOASK:
				noData();
				break;
			case SHOWQUESTION:
				// 显示 questionList 的数据 需要用到listview and adpter
				adapter = new QuestionListAdapter(DoctorUserActivity.this,
						questionList, order_list);
				order_list.setAdapter(adapter);
				break;
			default:
				break;
			}

		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.doctor_user_layout);
		mobilePhoneNum = UserInfoUtils.getUserProperty(this,
				HEALTHPASSPORT.MOBILEPHONE);
		initPages();
		getData();
		getQuestionList();
		request("0", 1);
	}

	private void initPages() {

		back = (Button) findViewById(R.id.btnBack);
		order_list = (ListView) findViewById(R.id.doctorlist);
		noData = (TextView) findViewById(R.id.nodata);
		introduce = (Button) findViewById(R.id.introduce);
		spinner_major = (Spinner) findViewById(R.id.zhuanye);
		name = (TextView) findViewById(R.id.name);
		geyan=(TextView)findViewById(R.id.geyan);
		dangan=(TextView)findViewById(R.id.jifen);
		headerImageView = (ImageView) findViewById(R.id.header);
		back.setOnClickListener(onClickListener);
		introduce.setOnClickListener(onClickListener);
		order_list.setOnItemClickListener(new OnItemClickListener() {


			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				consultationId=questionList.get(arg2).Id+"";
				Intent intent;
				intent=new Intent(DoctorUserActivity.this, AnswerActivity.class);
				intent.putExtra(consultationId, "consultationId");
				intent.putExtra(role, "role");
				startActivity(intent);
			}
		});
	}

	OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btnBack:
				// finish();
				TipsUtil.showExit(DoctorUserActivity.this);
				break;
			case R.id.introduce:// 跳转到医生介绍页面
				Intent intent;
				intent = new Intent(DoctorUserActivity.this,
						DoctorIntroduceActivity.class);
				intent.putExtra("introduce", intro);
				startActivity(intent);
				break;
			default:
				break;
			}
		}

	};

	/**
	 * 请求网络数据
	 */
	private void getData() {

		thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new RequestParamtersUtil().GetHealthCareByMobilePhone(
						mobilePhoneNum, new DefaultJSONData() {

							@Override
							public void parse(String result)
									throws JSONException {
								// TODO Auto-generated method stub
							}

							@Override
							public void parse(JSONObject object)
									throws JSONException {
								// TODO Auto-generated method stub
								Log.e("GetHealthCareByMobilePhoneObj",
										object.toString() + "");
								if (object.toString() != null) {
									docName = (String) object.get("Name")
											+ "     "
											+ (String) object
													.get("ProfessionalCategory")
											+ "     "
											+ (String) object
													.get("MembershipType");
									Log.e("1111", docName + "");
									headerUrl = (String) object
											.getString("PersonalPhotos");
									intro = (String) object
											.getString("Introduce");
									geyanString=(String)object.getString("Promise");
									haopingString=(String)object.getString("Praise");
									jifenString=(String)object.getString("Integral");
									handler.sendEmptyMessage(SUCCESS);
								}
							}

							@Override
							public void parse(JSONArray array)
									throws JSONException {
								// TODO Auto-generated method stub
								Log.e("GetHealthCareByMobilePhoneArr",
										array.toString() + "");
							}
						});
			}
		});
		thread.start();
	}

	/**
	 * 获取问题列表数据
	 */
	private void getQuestionList() {
		final String mobilePhone = UserInfoUtils.getUserProperty(this,
				HEALTHPASSPORT.MOBILEPHONE);
		thread = new Thread(new Runnable() {
			public void run() {
				new RequestParamtersUtil().GetQuestion(mobilePhone,
						new DefaultJSONData() {

							@Override
							public void parse(String result)
									throws JSONException {
								Log.e("GetQuestions", result.toString());
								if ("true".equals(result)) {
									handler.sendEmptyMessage(SUCCESS);
								} else if ("false".equals(result)) {
									handler.sendEmptyMessage(FAILE);
								} else if ("0".equals(result)) {
									handler.sendEmptyMessage(NOASK);
								} else {
									handler.sendEmptyMessage(ERROR);
								}
							}

							@Override
							public void parse(JSONObject object)
									throws JSONException {
								Log.e("GetQuestions", object.toString());
							}

							@Override
							public void parse(JSONArray array)
									throws JSONException {
								Log.e("GetQuestions", array.toString());
								if (array != null && array.length() > 0) {
									questionList = new ArrayList<QuestionBean>();
									for (int i = 0; i < array.length(); i++) {
										QuestionBean bean = new QuestionBean();
										bean.Evaluation = array
												.getJSONObject(i).getString(
														"Evaluation");
										bean.EvaluationState = array
												.getJSONObject(i).getString(
														"EvaluationState");
										bean.HealthyCareMobilephone = array
												.getJSONObject(i)
												.getString(
														"HealthyCareMobilephone");
										bean.Id = array.getJSONObject(i)
												.getInt("Id");
										bean.MobilePhone = array.getJSONObject(
												i).getString("MobilePhone");
										bean.ProfessionalCategoryId = array
												.getJSONObject(i)
												.getInt("ProfessionalCategoryId");
										bean.Question = array.getJSONObject(i)
												.getString("Question");
										// bean.QuestionTime=array.getJSONObject(i).getLong("QuestionTime");
										bean.State = array.getJSONObject(i)
												.getString("State");
										System.out.println(bean.Id);
										questionList.add(bean);
									}
									handler.sendEmptyMessage(SHOWQUESTION);
								}
							}
						});
			}
		});
		thread.start();
	}

	private void setData() {

		asyncImageLoader = new AsyncImageLoader();
		if (docName != null) {
			name.setText(docName);
		}
		if (headerUrl != null && !headerUrl.equals("")) {
			Drawable drawable = asyncImageLoader.loadImageFromUrl(headerUrl);
			if (drawable != null) {
				headerImageView.setImageDrawable(drawable);
			} else {
				headerImageView.setImageResource(R.drawable.head_scu);
			}
		}
		if(geyanString!=null&&!"".equals(geyanString)){
			geyan.setText("我的承诺："+geyanString);
		}
		dangan.setText("积分："+jifenString+"    "+"好评："+haopingString);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		TipsUtil.showExit(DoctorUserActivity.this);
		return super.onKeyDown(keyCode, event);

	}

	/**
	 * 无数据
	 */
	private void noData() {
		// TODO Auto-generated method stub
		order_list.setVisibility(View.GONE);
		noData.setVisibility(View.VISIBLE);
	}

	private void spinnerother() {// 其它的类别
		if (typeParse == null) {
			Log.e("000", "1000000000");
			return;
		}
		Log.e("000", "0000000000");
		spinner_major = (Spinner) this.findViewById(R.id.zhuanye);
		ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item,
				typeParse.nameListProfessionalCategory);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_major.setAdapter(adapter2);
		spinner_major
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int pos, long arg3) {
						professionalCategoryId = typeParse.typeListProfessionalCategory
								.get(pos).TypeId;
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						professionalCategoryId = typeParse.typeListProfessionalCategory
								.get(0).TypeId;
					}
				});
	}

	protected void request(final String provinceId, final int i) {
		final Context context = this;
		AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>() {

			@Override
			protected void onPreExecute() {
				if (dialog != null) {

				} else {
					dialog = ProgressDialog.show(context, "", "正在加载数据，请稍候...");
					dialog.setCancelable(true);
				}
				if (typeParse == null) {
					typeParse = new TypeParse();
				}

				parse = new AddressParse();
			}

			@Override
			protected Void doInBackground(Void... params) {
				new RequestParamtersUtil().GetByUpId(provinceId, parse);
				if (typeParse.typeListCertificateType != null) {

				} else {
					new RequestParamtersUtil().GetType(typeParse);
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {

				spinnerother();
				dialog.dismiss();
				dialog = null;
			}
		};
		asyncLoad.execute(null);
	}

}